package com.example.recyclerview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private List<Bean> data;
    private Context context;

    public MyAdapter(List<Bean> data, Context context) {
        this.data = data;
        this.context = context;
    }

    @NonNull

    @Override
    public MyViewHolder onCreateViewHolder(@NonNull  ViewGroup parent, int viewType) {
        View view=View.inflate(context,R.layout.recyclerview_item,null);
        //inflate最后一个参数如果root为null，attachToRoot将失去作用，设置任何值都没有意义。
        //如果root不为null，attachToRoot设为true，则会给加载的布局文件的指定一个父布局，即root。
        //如果root不为null，attachToRoot设为false，则会将布局文件最外层的所有layout属性进行设置，当该view被添加到父view当中时，这些layout属性会自动生效。
        //在不设置attachToRoot参数的情况下，如果root不为null，attachToRoot参数默认为true
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull  MyAdapter.MyViewHolder holder, int position) {
        holder.tv.setText(data.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return data==null?0:data.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        private TextView tv;
        public MyViewHolder(@NonNull  View itemView) {
            super(itemView);
            tv=itemView.findViewById(R.id.tv);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnIemClickListener!=null){
                        mOnIemClickListener.onRecyclerItemClick(getAdapterPosition());
                    }

                }
            });
        }
    }

    private OnRecyclerItemClickListener mOnIemClickListener;

    public  void setRecyclerItemClickListener(OnRecyclerItemClickListener listener){
        mOnIemClickListener=listener;
    }

    public interface OnRecyclerItemClickListener{
        void  onRecyclerItemClick(int position);

    }
}
